var dj_employee_detail_query = {};
var dc_employee_detail_query = {};

$(function () {

    grid_sum()
    grid_detail()

    bindEnterEvents();

    // 通过ajax请求数据url='employee/queryByFk'
    $.ajax({
        url: 'employee/queryByFk',
        type: 'GET', // 或者 'POST'，取决于后端接口要求
        data: {id: 4},
        success: function(response) {
            // 处理返回的数据
            console.log('挡车工员工数据:', response);
            dc_employee_detail_query=response;
        },
        error: function(xhr, status, error) {
            // 处理错误
            console.error('请求失败:', error);
        }
    });
    $.ajax({
        url: 'employee/queryByFk',
        type: 'GET', // 或者 'POST'，取决于后端接口要求
        data: {id: 5},
        success: function(response) {
            // 处理返回的数据
            console.log('打卷工员工数据:', response);
            dj_employee_detail_query=response;
        },
        error: function(xhr, status, error) {
            // 处理错误
            console.error('请求失败:', error);
        }
    });

})


//获取汇总数据
function getgriddata() {
    let bBCFC=$('#bBCFC').textbox('getValue')
    let jrkdraftitemid=$('#jrkdraftitemid').textbox('getValue')
    // 两个参数不能同时为空 判断
    if(!jrkdraftitemid && !bBCFC){
        $.messager.alert('提示', '请输入卡片号或者标签二维码编号！', 'info');
        return;
    }

    $.messager.progress({title: '', msg: '请稍等...', interval: 5000});
    $.ajax({
        url: "customize/callProc",
        type: 'post',
        data: JSON.stringify(['usp_getjrk_detail_query',1,bBCFC,jrkdraftitemid]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let  data=cdata.data;
            console.log(data);
            for (let i = 0; i < data.length; i++) {
                let jrk = data[i];
                if (isNull(jrk.B_FPDID, 0) == 0 && isNull(jrk.B_CreateDate, 0) == 0) {
                    jrk.status = '库存';
                    jrk.statusDate = data.B_Date;

                }
                if (isNull(jrk.B_FPDID, 0) !== 0) {
                    jrk.status = '已发货';
                    jrk.statusDate = data.B_DTRK;

                }
                if (isNull(jrk.B_CreateDate, 0) !== 0) {
                    jrk.status = '已删除';
                    jrk.statusDate = data.B_CreateDate;

                }
            }
            $('#v_grid_sum').datagrid('loadData', data);
            $('#v_grid_detail').datagrid('loadData', []);
        }, complete: function () {
            $.messager.progress('close');
        }

    })
}

/**
 * 判断是否null
 * @param data
 * 为空可自定义 val 值
 */
function isNull(data,val){
    return (data == "" || data == undefined || data == null || data == NaN) ? val : data;
}

// 获取明细数据
function getgriddata_detail(dataItem) {
    $.messager.progress({title: '', msg: '请稍等...', interval: 5000});
    $.ajax({
        url: "customize/callProc",
        type: 'post',
        data: JSON.stringify(['usp_getjrk_detail_query',2,dataItem.B_BCFC,dataItem.B_jrkbilldraftitemid]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let  data=cdata.data;
            console.log(data);
            $('#v_grid_detail').datagrid('loadData', data);
        }, complete: function () {
            $.messager.progress('close');
        }
    })
}

/**
 * 2025-5-9 16:55:27 LIN
 * 第一个标签页 - 整经工产量
 */
function grid_sum() {
    $('#v_grid_sum').datagrid({
        data: [],
        striped: true,
        autoSave: false,
        sortable: true,
        fit:true,
        fitColumns:false,
        ctrlSelect:true,
        rownumbers:true,
        remoteSort: false,
        singleSelect: true,
        showFooter: true,
        idField: 'id',
        columns:[[
            {field: 'B_BCFC', title: '卡片号', align: 'center',width:80},
            {field: 'B_jrkbilldraftitemid', title: '二维码编号', align: 'center',width:80},
            {field: 'B_GJ', title: '重量', align: 'center',width:65,formatter: formatNumber},
            {field: 'B_MS', title: '米数', align: 'center',width:65,formatter: formatNumber},
            // {field: 'B_JTH', title: '机台号', align: 'center',width:50},
            {field: 'B_DJPeople', title: '打卷工', align: 'center',width:80},
            {field: 'B_Class', title: '挡车工', align: 'center',width:150},
            {field: 'B_Date', title: '打卷时间', align: 'center',width:150},
            {field: 'status', title: '状态', align: 'center',width:80},
            {field: 'B_Date', title: '状态时间', align: 'center',width:150},
            {field: 'B_CN', title: '打卷电脑', align: 'center',width:95},
        ]],
        onLoadSuccess: function (data) {
            let rows = $('#v_grid_sum').datagrid("getRows");
            let ms = 0, qty = 0,money = 0;
            for (let i = 0; i < rows.length; i++) {
                ms += parseFloat(rows[i].B_MS ? rows[i].B_MS : 0);
                qty += parseFloat(rows[i].B_GJ ? rows[i].B_GJ : 0);
            }
            $('#v_grid_sum').datagrid('reloadFooter', [{date: '合计',B_MS: ms,B_GJ:qty}]);
        },
        onClickRow: function (index, row) {
            getgriddata_detail(row)
        },

    });
}

function grid_detail() {
    $('#v_grid_detail').datagrid({
        data: [],
        striped: true,
        autoSave: false,
        sortable: true,
        fit:true,
        fitColumns:true,
        ctrlSelect:true,
        rownumbers:true,
        remoteSort: false,
        singleSelect: true,
        showFooter: true,
        idField: 'id',
        columns:[[
            {field: 'B_People', title: '挡车工', align: 'center',width:80},
            {field: 'B_MS', title: '米数', align: 'center',width:65,formatter: formatNumber},
            {field: 'B_Date', title: '时间', align: 'center',width:200}
        ]],
        onLoadSuccess: function (data) {
            let rows = $('#v_grid_detail').datagrid("getRows");
            let ms = 0, qty = 0,money = 0;
            for (let i = 0; i < rows.length; i++) {
                ms += parseFloat(rows[i].B_MS ? rows[i].B_MS : 0);
                // qty += parseFloat(rows[i].B_GJ ? rows[i].B_GJ : 0);
            }
            $('#v_grid_detail').datagrid('reloadFooter', [{date: '合计',B_MS: ms}]);
        },
    });
}


/**
 * **********************************************************************************************************************
 * 挡车工和打卷工的明细
 */
function setgrid() {
    $('#v_grid_sum01').edatagrid({
        data: [],
        striped: true,
        autoSave: false,
        sortable: true,
        fit:true,
        fitColumns:true,
        ctrlSelect:true,
        rownumbers:true,
        remoteSort: false,
        singleSelect: true,
        idField: 'id',
        columns:[[
            {field: 'B_jrkbilldraftitemid', title: '二维码编号', align: 'center',width:80},
            {field: 'B_DJPeople', title: '打卷工', align: 'center',width:80,
                editor: {
                    type: 'combobox', options: {
                        data: dj_employee_detail_query,
                        panelHeight: 300,
                        textField: 'empName',
                        valueField: 'empName',
                        required: true,
                        limitToList: true
                    }
                }
            },
            {field: 'B_GJ', title: '重量', align: 'center',width:65,formatter: formatNumber,
                editor: {
                    type: 'textbox', options: {required: true}
                }
            }

        ]],
    });

    $('#v_grid_detail01').edatagrid({
        data: [],
        striped: true,
        autoSave: false,
        sortable: true,
        fit:true,
        fitColumns:true,
        ctrlSelect:true,
        rownumbers:true,
        remoteSort: false,
        singleSelect: true,
        showFooter: true,
        idField: 'id',
        columns:[[
            {field: 'B_People', title: '挡车工', align: 'center',width:80,
                editor: {
                    type: 'combobox', options: {
                        data: dc_employee_detail_query,
                        panelHeight: 300,
                        textField: 'empName',
                        valueField: 'empName',
                        required: true,
                        limitToList: true
                    }
                }
            },
            {field: 'B_MS', title: '米数', align: 'center',width:65,formatter: formatNumber,
                editor: {
                    type: 'textbox', options: {required: true}
                }
            }
        ]]
    });

}

function formatNumber(value, row, index) {
     return value?parseFloat(value).toFixed(1):'';
}

function formatNumber2(value, row, index) {
    return value?parseFloat(value).toFixed(2):'';
}
function formatNumber3(value, row, index) {
    return value?parseFloat(value).toFixed(3):'';
}


function opengridDate(){

    var selectedRow = $('#v_grid_sum').datagrid('getSelected');
    var allRows = $('#v_grid_detail').datagrid('getRows');
    if (selectedRow) {
        $('#dj_detail').dialog('open');
        setgrid()
        $('#v_grid_sum01').datagrid('loadData', [selectedRow]);
        $('#v_grid_detail01').datagrid('loadData', allRows);
    } else {
        $.messager.alert('提示', '没有选中任何行！', 'info');
    }
}


function savegrid() {
    let dateobj={};
    $('#v_grid_sum01').edatagrid('saveRow');
    $('#v_grid_detail01').edatagrid('saveRow');

    var allRows01 = $('#v_grid_sum01').datagrid('getRows');
    var allRows02 = $('#v_grid_detail01').datagrid('getRows');

    // 将数据保存到数据库
    for (let i = 0; i < allRows01.length; i++) {
        dateobj.bItemID=allRows01[i].B_ItemID;
        dateobj.bGJ=allRows01[i].B_GJ;
        dateobj.bDJPeople=allRows01[i].B_DJPeople;
    }
    let detailList=[];
    let mssum=0;
    let bClass='';
    for (let i = 0; i < allRows02.length; i++) {
        let obj={};
        obj.id=allRows02[i].id;
        obj.bMS=allRows02[i].B_MS;
        obj.bPeople=allRows02[i].B_People;
        mssum=mssum+parseFloat(allRows02[i].B_MS);
        if(i==0){
            bClass=allRows02[i].B_People;
        }else{
            bClass=bClass+','+allRows02[i].B_People;
        }

        detailList.push(obj);

    }

    dateobj.bMS=mssum;
    dateobj.bClass=bClass;
    dateobj.detailList=detailList;
    console.log(dateobj)
    $.ajax({
        url: 'gjrkbillCp/updateByJrkCp',
        type: 'POST',
        data:  JSON.stringify(dateobj),
        dataType: 'json',
        contentType: "application/json;charset=UTF-8",
        success: function (data) {
            console.log(data);

            $('#dj_detail').dialog('close');
            btn_search()
        }
    })

}


/**
 * **********************************************************************************************************************
 */


//打印发货单
function btn_print_bill() {
    let reportlets = [];
    $.get('customize/getDatabase', {}, data => {
        if (data.success) {
            switch (getCurrentIndex()) {
                case 0:
                    break;
                case 1:
                    let kGrid = $('#v_grid_0').data('kendoGrid');
                    var selectedRows = kGrid.select();
                    for (let i = 0; i < selectedRows.length; i++) {
                        let dataItem = kGrid.dataItem(selectedRows[i]);
                        let Obj= {
                            reportlet: `${data.data}/invoice-cpfh.cpt`,
                            id: dataItem.id
                        };
                        reportlets.push(Obj);
                    }
                    console.log(reportlets);
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                    break;
                case 2:
                    break;
            }
        }
    }, 'json');
}

//库存明细获取数据
function getckdetail(m_FPDID,m_barcode, dataItem) {
    $.messager.progress({title: '', msg: '请稍等...', interval: 5000});
    let index = getCurrentIndex();
    if (index == 1) {
        $.ajax({
            url: "cpBillfh/listQuery",
            type: 'GET',
            data: {mainId: dataItem.id},
            success: function (cdata) {
                if (cdata.length) {
                    $('#fh_dg_bill').datagrid('clearSelections');
                    $('#fh_dg_bill').datagrid('loadData', cdata);
                }
            }, complete: function () {
                $.messager.progress('close');
            }
        })
    } else {
        $.ajax({
            url: "customize/callProc",
            type: 'post',
            data: JSON.stringify(['usp_getcpjrkdetail',m_FPDID,m_barcode]),
            contentType: "application/json;charset=UTF-8",
            success: function (cdata) {
                let  data=cdata.data;
                if (Number(m_FPDID)>0){
                    $('#fh_dg').datagrid('clearSelections');
                    $('#fh_dg').datagrid('loadData', data);
                }else{
                    $('#ck_dg').datagrid('clearSelections');
                    $('#ck_dg').datagrid('loadData', data);
                }
            }, complete: function () {
                $.messager.progress('close');
            }
        })
    }
}
//清除过滤
function btn_cancel_filter() {
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid_detail').data('kendoGrid').dataSource.filter({});
            break;
        case 1:
            $('#v_grid_detail01').data('kendoGrid').dataSource.filter({});
            break;
        case 2:
            $('#v_grid_detail02').data('kendoGrid').dataSource.filter({});
            break;
        case 3:
            $('#v_grid_detail03').data('kendoGrid').dataSource.filter({});
            break;
    }
}
//查询事件
function btn_search() {
    getgriddata()
}

/********************************************
 */
//获取标签页序号
function getCurrentIndex() {
    let tab = $('#tabs').tabs('getSelected');
    let index = $('#tabs').tabs('getTabIndex', tab);
    return index;
}
//获取当前标签页的网格对象
function getSelectedGrid() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid_sum';
            break;
        case 1:
            kendoGridID = '#v_grid_sum01';
            break;
        case 2:
            kendoGridID = '#v_grid_sum02';
            break;
        case 3:
            kendoGridID = '#v_grid_sum03';
            break;
    }
    return $(kendoGridID).data('kendoGrid');
}

function getSelectedGridDetail() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid_detail';
            break;
        case 1:
            kendoGridID = '#v_grid_detail01';
            break;
        case 2:
            kendoGridID = '#v_grid_detail02';
            break;
        case 3:
            kendoGridID = '#v_grid_detail03';
            break;
    }
    return $(kendoGridID).data('kendoGrid');
}



//打印
function btn_print() {
    let reportlets = [];
    $.get('customize/getDatabase', {}, data => {
        if (data.success) {

            var selectedRow = $('#v_grid_sum').datagrid('getSelected');
            if (selectedRow) {
                let Obj= {
                    reportlet: `${data.data}/jrk_label.cpt`,
                    bItemID: selectedRow.B_ItemID,
                    database: data.data
                };
                reportlets.push(Obj);

                console.log(reportlets);
                window.parent.FR.doURLPDFPrint({
                    url: $(window.parent.document.body).data('report_url'),
                    isPopUp: false,
                    data: {
                        reportlets: reportlets
                    }
                })
            } else {
                $.messager.alert('提示', '没有选中任何行！', 'info');
            }

        }
    }, 'json');
}

//z自动列设置
function btn_open_column_list() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid_detail';
            break;
        case 1:
            kendoGridID = '#v_grid_2';
            break;
    }
    let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列',
                                         onClose:function(){$(this).dialog('destroy')}   " 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        $(kendoGridID).data('kendoGrid').showColumn(opts.name);
                    } else {
                        $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}
//导出
function btn_export_excel() {
    switch (getCurrentIndex()) {
        case 0:
            // $('#v_grid_sum').data('kendoGrid').saveAsExcel();
            $('#v_grid_detail').data('kendoGrid').saveAsExcel();
            break;
        case 1:
            // $('#v_grid_sum01').data('kendoGrid').saveAsExcel();
            $('#v_grid_detail01').data('kendoGrid').saveAsExcel();
            break;
        case 2:
            // $('#v_grid_sum02').data('kendoGrid').saveAsExcel();
            $('#v_grid_detail02').data('kendoGrid').saveAsExcel();
            break;
        case 3:
            // $('#v_grid_sum03').data('kendoGrid').saveAsExcel();
            $('#v_grid_detail03').data('kendoGrid').saveAsExcel();
            break;
    }
}


function btn_close() {
    window.parent.closeTab();
}
